import { useState, useMemo } from 'react'
import {
  Table,
  Input,
  Select,
  DatePicker,
  Button,
  Space,
  Modal,
  Form,
  InputNumber,
  message,
  Popconfirm,
  Tag,
  Typography,
  Tooltip,
} from 'antd'
import {
  SearchOutlined,
  EditOutlined,
  DeleteOutlined,
  ReloadOutlined,
} from '@ant-design/icons'
import dayjs from 'dayjs'
import { validateWorkTimeData } from '../utils/dataParser'

const { RangePicker } = DatePicker
const { Option } = Select
const { TextArea } = Input
const { Text } = Typography

const WorkTimeTable = ({
  data = [],
  originalData = [],
  onFilterData,
  onDeleteRecord,
  onEditRecord,
}) => {
  const [filters, setFilters] = useState({
    keyword: '',
    project: 'all',
    product: 'all',
    dateRange: null,
  })
  const [editingRecord, setEditingRecord] = useState(null)
  const [editModalVisible, setEditModalVisible] = useState(false)
  const [editForm] = Form.useForm()
  const [loading, setLoading] = useState(false)

  // 获取项目和产品选项
  const filterOptions = useMemo(() => {
    const projects = new Set()
    const products = new Set()

    originalData.forEach((item) => {
      if (item.project) projects.add(item.project)
      if (item.product) products.add(item.product)
    })

    return {
      projects: Array.from(projects).sort(),
      products: Array.from(products).sort(),
    }
  }, [originalData])

  // 处理筛选
  const handleFilter = () => {
    onFilterData(filters)
  }

  // 重置筛选
  const handleResetFilter = () => {
    const resetFilters = {
      keyword: '',
      project: 'all',
      product: 'all',
      dateRange: null,
    }
    setFilters(resetFilters)
    onFilterData(resetFilters)
  }

  // 处理编辑
  const handleEdit = (record) => {
    setEditingRecord(record)
    editForm.setFieldsValue({
      ...record,
      date: dayjs(record.date),
    })
    setEditModalVisible(true)
  }

  // 处理编辑提交
  const handleEditSubmit = async (values) => {
    setLoading(true)
    try {
      const updatedRecord = {
        ...values,
        date: values.date.format('YYYY-MM-DD'),
        hours: values.hours || 0,
        remaining: values.remaining || 0,
        content: values.content || '',
        object: values.object || '',
        product: values.product || '',
        executor: values.executor || '',
        project: values.project || '',
      }

      if (!validateWorkTimeData(updatedRecord)) {
        message.error('数据验证失败，请检查必填项')
        return
      }

      onEditRecord(editingRecord.id, updatedRecord)
      setEditModalVisible(false)
      setEditingRecord(null)
      editForm.resetFields()
      message.success('记录更新成功')
    } catch (error) {
      console.error('更新记录失败:', error)
      message.error('更新失败，请重试')
    } finally {
      setLoading(false)
    }
  }

  // 处理删除
  const handleDelete = (record) => {
    onDeleteRecord(record.id)
    message.success('记录删除成功')
  }

  // 表格列定义
  const columns = [
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date',
      width: 120,
      sorter: (a, b) => a.date.localeCompare(b.date),
      render: (date) => <Text>{date}</Text>,
    },
    {
      title: '工作内容',
      dataIndex: 'content',
      key: 'content',
      width: 300,
      ellipsis: true,
      render: (content) => <Tooltip title={content}>{content}</Tooltip>,
    },
    {
      title: '耗时(h)',
      dataIndex: 'hours',
      key: 'hours',
      width: 80,
      sorter: (a, b) => a.hours - b.hours,
      render: (hours) => <Text strong>{hours}</Text>,
    },
    {
      title: '剩余(h)',
      dataIndex: 'remaining',
      key: 'remaining',
      width: 80,
      sorter: (a, b) => a.remaining - b.remaining,
      render: (remaining) => <Text>{remaining}</Text>,
    },
    {
      title: '对象',
      dataIndex: 'object',
      key: 'object',
      width: 200,
      ellipsis: true,
      render: (object) => <Tooltip title={object}>{object}</Tooltip>,
    },
    {
      title: '产品',
      dataIndex: 'product',
      key: 'product',
      width: 120,
      render: (product) => <Tag color='blue'>{product || '未分类'}</Tag>,
    },
    {
      title: '执行',
      dataIndex: 'executor',
      key: 'executor',
      width: 100,
      render: (executor) => <Text>{executor}</Text>,
    },
    {
      title: '项目',
      dataIndex: 'project',
      key: 'project',
      width: 250,
      render: (project) => <Tag color='green'>{project || '未分类'}</Tag>,
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      fixed: 'right',
      render: (_, record) => (
        <Space size='small'>
          <Button
            type='primary'
            icon={<EditOutlined />}
            size='small'
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title='确定删除此记录吗？'
            onConfirm={() => handleDelete(record)}
            okText='确定'
            cancelText='取消'
          >
            <Button
              type='primary'
              danger
              icon={<DeleteOutlined />}
              size='small'
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ]

  return (
    <div>
      {/* 筛选区域 */}
      <div className='filters-row'>
        <div className='filter-item'>
          <Input
            placeholder='搜索工作内容或对象'
            value={filters.keyword}
            onChange={(e) =>
              setFilters((prev) => ({ ...prev, keyword: e.target.value }))
            }
            prefix={<SearchOutlined />}
            allowClear
          />
        </div>

        <div className='filter-item'>
          <Select
            placeholder='选择项目'
            value={filters.project}
            onChange={(value) =>
              setFilters((prev) => ({ ...prev, project: value }))
            }
            allowClear
          >
            <Option value='all'>全部项目</Option>
            {filterOptions.projects.map((project) => (
              <Option key={project} value={project}>
                {project}
              </Option>
            ))}
          </Select>
        </div>

        <div className='filter-item'>
          <Select
            placeholder='选择产品'
            value={filters.product}
            onChange={(value) =>
              setFilters((prev) => ({ ...prev, product: value }))
            }
            allowClear
          >
            <Option value='all'>全部产品</Option>
            {filterOptions.products.map((product) => (
              <Option key={product} value={product}>
                {product}
              </Option>
            ))}
          </Select>
        </div>

        <div className='filter-item'>
          <RangePicker
            value={filters.dateRange}
            onChange={(dates) =>
              setFilters((prev) => ({ ...prev, dateRange: dates }))
            }
            format='YYYY-MM-DD'
            placeholder={['开始日期', '结束日期']}
          />
        </div>

        <div>
          <Space>
            <Button
              type='primary'
              icon={<SearchOutlined />}
              onClick={handleFilter}
            >
              搜索
            </Button>
            <Button icon={<ReloadOutlined />} onClick={handleResetFilter}>
              重置
            </Button>
          </Space>
        </div>
      </div>

      {/* 表格 */}
      <div className='table-container'>
        <Table
          columns={columns}
          dataSource={data}
          rowKey='id'
          scroll={{ x: 1200 }}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`,
            pageSizeOptions: ['10', '20', '50', '100'],
            defaultPageSize: 20,
          }}
          size='small'
        />
      </div>

      {/* 编辑模态框 */}
      <Modal
        title='编辑工时记录'
        open={editModalVisible}
        onOk={() => editForm.submit()}
        onCancel={() => {
          setEditModalVisible(false)
          setEditingRecord(null)
          editForm.resetFields()
        }}
        width={800}
        confirmLoading={loading}
      >
        <Form form={editForm} layout='vertical' onFinish={handleEditSubmit}>
          <Form.Item
            name='date'
            label='日期'
            rules={[{ required: true, message: '请选择日期' }]}
          >
            <DatePicker style={{ width: '100%' }} format='YYYY-MM-DD' />
          </Form.Item>

          <Form.Item
            name='content'
            label='工作内容'
            rules={[
              { required: true, message: '请输入工作内容' },
              { min: 5, message: '工作内容至少5个字符' },
            ]}
          >
            <TextArea rows={3} showCount maxLength={500} />
          </Form.Item>

          <div style={{ display: 'flex', gap: '16px' }}>
            <Form.Item
              name='hours'
              label='耗时（小时）'
              rules={[
                { required: true, message: '请输入耗时' },
                {
                  type: 'number',
                  min: 0,
                  max: 24,
                  message: '耗时必须在0-24小时之间',
                },
              ]}
              style={{ flex: 1 }}
            >
              <InputNumber
                style={{ width: '100%' }}
                min={0}
                max={24}
                step={0.5}
                precision={1}
              />
            </Form.Item>

            <Form.Item
              name='remaining'
              label='剩余（小时）'
              rules={[
                { type: 'number', min: 0, message: '剩余时间不能为负数' },
              ]}
              style={{ flex: 1 }}
            >
              <InputNumber
                style={{ width: '100%' }}
                min={0}
                step={0.5}
                precision={1}
              />
            </Form.Item>
          </div>

          <Form.Item name='object' label='对象'>
            <Input />
          </Form.Item>

          <div style={{ display: 'flex', gap: '16px' }}>
            <Form.Item name='product' label='产品' style={{ flex: 1 }}>
              <Input />
            </Form.Item>

            <Form.Item name='executor' label='执行' style={{ flex: 1 }}>
              <Input />
            </Form.Item>
          </div>

          <Form.Item name='project' label='项目'>
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default WorkTimeTable
